import md5 from 'md5';
import router from '@system.router';
import prompt from '@system.prompt';
import { sleep, register } from "../../service.js";

export default {
    data: {
        loading: false,
        username: "",
        password: "",
        confirmpass: "",
    },
    onInit() {
        router.push({
            uri: 'pages/imagepage/imagepage'
        })
    },
    back() {
        router.replace({
            uri: "pages/index/index",
        });
    },
    // 监听用户输入框中数据信息的变化
    usernameChange(e) {
        this.username = e.value;
    },
    // 监听密码输入框中数据信息的变化
    passwordChange(e) {
        this.password = e.value;
    },
    confirmpassChange(e) {
        this.confirmpass = e.value;
    },
    /**
     * 点击输入框操作
     *
     * @param e
     * @return 点击输入框操作
     */
    enterkeyClick() {
        this.login();
    },
    /**
     * 登录点击操作
     */
     registerClick() {
        this.register();
    },
    async register() {
        if (!this.username) {
            this.$element("username").showError({
                error: this.$t('login.username.placeholder')
            });
            return
        }

        if (!this.password) {
            this.$element("password").showError({
                error: this.$t('login.password.placeholder')
            });
            return
        }

        if (!this.confirmpass) {
            this.$element("confirmpass").showError({
                error: this.$t('login.confirmpass.placeholder')
            });
            return
        }

        if (this.confirmpass !== this.password) {
            this.$element("confirmpass").showError({
                error: this.$t('login.confirmpass.notequal')
            });
            return
        }

        if (this.loading) return;
        this.loading = true;
        const res = await register({ username: this.username, password: md5(this.password) })
        if (res) {
            prompt.showToast({
                message: '注册成功！',
                duration: 2000,
            });

            await sleep(2000);
            this.loading = false;
            this.username = "";
            this.password = "";
            this.confirmpass = "";

            router.replace({
                uri: "pages/index/index",
            });
        }
    }
}
